﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MvcPatch.Html
{
    public static class PartialExtensions
    {
        // Renders the partial view with the parent's view data
        public static string Partial(this HtmlHelper htmlHelper, string partialViewName)
        {
            return htmlHelper.PartialInternal(partialViewName, htmlHelper.ViewData, null, ViewEngines.Engines);
        }

        // Renders the partial view with the given view data
        public static string Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData)
        {
            return htmlHelper.PartialInternal(partialViewName, viewData, null, ViewEngines.Engines);
        }

        // Renders the partial view with an empty view data and the given model
        public static string Partial(this HtmlHelper htmlHelper, string partialViewName, object model)
        {
            return htmlHelper.PartialInternal(partialViewName, htmlHelper.ViewData, model, ViewEngines.Engines);
        }

        // Renders the partial view with a copy of the given view data plus the given model
        public static string Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData)
        {
            return htmlHelper.PartialInternal(partialViewName, viewData, model, ViewEngines.Engines);
        }

        internal static string PartialInternal(
            this HtmlHelper htmlHelper,
            string partialViewName,
            ViewDataDictionary viewData,
            object model,
            ViewEngineCollection viewEngineCollection)
        {
            var output = new StringWriter();
            htmlHelper.RenderPartial(partialViewName, model, viewData, output);
            return output.ToString();
        }
    }
}
